package product_type

import (
	"context"
	"gitee.com/zyw0605688_admin/gozero/product_service/model"

	"gitee.com/zyw0605688_admin/gozero/product_service/internal/svc"
	"gitee.com/zyw0605688_admin/gozero/product_service/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductTypeListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductTypeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductTypeListLogic {
	return &ProductTypeListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductTypeListLogic) ProductTypeList(req *types.ProductTypeListRequest) (resp *types.ProductTypeListResponse, err error) {
	list := []model.ProductType{}
	total := int64(0)
	sqlQuery := l.svcCtx.DB.Model(&model.ProductType{})
	totalQuery := l.svcCtx.DB.Model(&model.ProductType{})
	if req.PageSize > 0 && req.PageNum > 0 {
		sqlQuery.Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize)
	}
	if req.ProductTypeName != nil {
		sqlQuery.Where("product_type_name like ?", "%"+*req.ProductTypeName+"%")
		totalQuery.Where("product_type_name like ?", "%"+*req.ProductTypeName+"%")
	}
	err = sqlQuery.Find(&list).Error
	err = totalQuery.Count(&total).Error
	if err != nil {
		return nil, err
	}
	resList := []types.ProductTypeDetailResponse{}
	for _, v := range list {
		resList = append(resList, types.ProductTypeDetailResponse{
			Id:              v.Id,
			ProductTypeName: v.ProductTypeName,
			ProductTypeCode: v.ProductTypeCode,
			ProductTypeDesc: v.ProductTypeDesc,
			SortCode:        v.SortCode,
			CreatedAt:       v.CreatedAt,
		})
	}
	resp = &types.ProductTypeListResponse{
		List:  resList,
		Total: total,
	}
	return
}
